package com.song.boot.springstudy.netty.fileregion;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.handler.stream.ChunkedFile;

import java.io.File;
import java.io.RandomAccessFile;
//Netty 零拷贝文件传输案例：FileRegion vs 传统堆内存复制
public class FileServer {

    static final boolean SSL = System.getProperty("ssl") != null;
    static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8992" : "8023"));
    static final String FILE_PATH = System.getProperty("file", "large_file.dat");  // 相对路径下的

    public static void main(String[] args) throws Exception {
        // 配置SSL
        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = null;
        }

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 protected void initChannel(SocketChannel ch) throws Exception {
                     ChannelPipeline p = ch.pipeline();
                     if (sslCtx != null) {
                         p.addLast(sslCtx.newHandler(ch.alloc()));
                     }
                     p.addLast(
                             new StringEncoder(),
                             new LineBasedFrameDecoder(8192),
                             new StringDecoder(),
                             new FileServerHandler());
                 }
             });

            ChannelFuture f = b.bind(PORT).sync();
            System.out.println("File server started at port " + PORT);
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static class FileServerHandler extends SimpleChannelInboundHandler<String> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            if ("get_file".equals(msg)) {
                // 传统方式 - 使用堆内存复制
                sendFileWithHeapBuffer(ctx);
                
                // 零拷贝方式 - 使用FileRegion (取消下面注释可以测试)
                // sendFileWithZeroCopy(ctx);
            }
        }

        // 传统方式 - 使用堆内存复制
        private void sendFileWithHeapBuffer(ChannelHandlerContext ctx) throws Exception {
            RandomAccessFile raf = new RandomAccessFile(FILE_PATH, "r");
            long fileLength = raf.length();
            
            // 将文件内容读取到堆内存
            byte[] fileContent = new byte[(int) fileLength];
            raf.read(fileContent);
            raf.close();
            
            // 通过堆内存缓冲区传输
            ctx.writeAndFlush(ctx.alloc().buffer().writeBytes(fileContent))
               .addListener(future -> {
                   if (future.isSuccess()) {
                       System.out.println("传统堆内存复制方式传输完成");
                   }
               });
        }

        // 零拷贝方式 - 使用FileRegion
        private void sendFileWithZeroCopy(ChannelHandlerContext ctx) throws Exception {
            RandomAccessFile raf = new RandomAccessFile(FILE_PATH, "r");
            long fileLength = raf.length();
            
            // 使用FileRegion实现零拷贝
            FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength);
            
            ctx.writeAndFlush(region).addListener(future -> {
                raf.close();
                if (future.isSuccess()) {
                    System.out.println("零拷贝方式传输完成");
                }
            });
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            cause.printStackTrace();
            ctx.close();
        }
    }
}